﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MultiplayerDice.Implementation;
using MultiplayerDice.Implementation.BusinessEvent;
using System.Web.Security;
using MultiplayerDice.Implementation.Command;
using System.Data;

namespace MultiplayerDice.Components
{
    public partial class OpenGames : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var gameId = (Guid)(e.CommandSource as GridView).DataKeys[(int.Parse(e.CommandArgument as string))].Value;
            var diced = Dice.Throw();
            EventRaiser.Raise(new ExistingGameEndedCommand()
            {
                Diced = diced,
                GameId = gameId,
                PlayerName = Membership.GetUser().UserName
            });
            EndedGameIds.Add(gameId);
            needsBinding = true;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (needsBinding)
                GridView1.DataBind();
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null && e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.DataItem != null && e.Row.DataItem is DataRowView)
                {
                    var dataRow = e.Row.DataItem as DataRowView;
                    if (EndedGameIds.Contains((Guid)dataRow.Row["GameId"]))
                    {
                        e.Row.Enabled = false;
                        e.Row.Cells[0].Text = "Sended ";
                    }
                }
            }
        }

        private bool needsBinding;
        public List<Guid> EndedGameIds
        {
            get
            {
                if (Session["EndedGameIds"] == null)
                    Session["EndedGameIds"] = new List<Guid>();
                return Session["EndedGameIds"] as List<Guid>;
            }
        }
    }
}